package swimv2gm.client.requests;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.session.WorkRequestManager;

/**
 * Servlet implementation class SendRequest
 */
public class SendRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		WorkRequestManager man;
		try {
			man = (WorkRequestManager)InitialContext.doLookup("WorkRequestManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}
		long dest = -1,field = -1;
		try {
			dest = Long.parseLong(request.getParameter("dest"));
			field = Long.parseLong(request.getParameter("field"));
		} catch (NumberFormatException e) {
			response.sendRedirect("/SWIMv2gm/requests/RequestCreation?error=true&dest=" + dest);
		}
		String desc = request.getParameter("desc");

		boolean success;

		if (request.getSession().getAttribute("user") != null) {
			long mitt = (Long)request.getSession().getAttribute("user");
			success = man.createRequest(mitt,dest,field,desc);
		}
		else if (request.getParameter("contact") != null) {
			String mitt = request.getParameter("contact");
			success = man.createRequest(mitt,dest,field,desc);
		}
		else {
			success = false;
		}

		if (success) {
			response.sendRedirect("/SWIMv2gm/user/Profile?uid=" + dest + "&executed=workrequest&success=true");
		}
		else {
			response.sendRedirect("/SWIMv2gm/requests/RequestCreation?error=true&dest=" + dest);
		}
	}

}
